package com.sparrow.rpc;

import com.sparrow.rpc.domain.RpcNode;
import com.sparrow.rpc.manager.RpcClientManager;
import com.sparrow.rpc.manager.RpcNodeManager;
import com.sparrow.rpc.socket.RpcServer;
import com.sparrow.rpc.socket.handler.RpcServerHandler;
import com.sparrow.rpc.socket.init.RpcServerInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.sparrow.rpc")
public class SparrowRpcAutoConfig {
    @Bean
    public RpcServerHandler rpcServerHandler() {
        return new RpcServerHandler();
    }

    @Bean
    public RpcServerInitializer rpcServerInitializer(RpcServerHandler rpcServerHandler) {
        RpcServerInitializer initializer = new RpcServerInitializer();
        initializer.setRpcServerHandler(rpcServerHandler);
        return initializer;
    }

    @Bean
    public RpcServer rpcServer(RpcServerInitializer rpcServerInitializer, RpcNodeManager rpcNodeManager, RpcClientManager clientManager) {
        RpcNode self = rpcNodeManager.getSelf();
        //rpc server bind port
        RpcServer rpcServer = new RpcServer();
        rpcServer.setNode(self);
        rpcServer.setChannelInitializer(rpcServerInitializer);
        rpcServer.start(self.getPort());
        return rpcServer;
    }
}

